package cn.yunhe.controller;

import cn.yunhe.entity.Role;
import cn.yunhe.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/findAll")
    public String findAll(Model Model,
                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "5") Integer size) {
        PageHelper.startPage(page, size);
        List<Role> roleList = roleService.findAll();
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        Model.addAttribute("pageInfo", pageInfo);
        return "role-list";

    }

    @RequestMapping("/save")
    public String save(Role role) {
        roleService.insertRole(role);
        return "redirect:findAll";
    }

    @RequestMapping("/findRoleByIdAndAllPermission")
    public String findRoleByIdAndAllPermission(Model model, Integer id) {
        Role role = roleService.findRoleByIdAndAllPermission(id);
        model.addAttribute("role", role);
        model.addAttribute("permissionList", role.getPermissions());
        return "role-permission-add";

    }

    @RequestMapping("/addPermissionToRole")
    public String addPermissionToRole(Integer[] ids, Integer roleId) {
        roleService.addPermissionToRole(ids, roleId);
        return "redirect:findAll";
    }

    @RequestMapping("/findById")
    public String findById(Model model, Integer id) {
        Role role = roleService.findRoleById(id);
        model.addAttribute("role",role);
        model.addAttribute("permission",role.getPermissions());
        return "role-show";

    }

    @RequestMapping("/deleteRole")
    public String deleteRole(Integer id){
        roleService.deleteRole(id);
        return  "redirect:findAll";

    }
}
